package com.one.blocks.rbac.security;

import com.one.blocks.rbac.domain.SysRole;
import com.one.blocks.rbac.enums.RoleTypeEnum;
import com.one.blocks.rbac.manager.SysMenuManager;
import com.one.blocks.rbac.manager.SysRoleManager;
import com.one.blocks.rbac.util.SubjectRoleHelper;
import com.one.blocks.security.authc.AccessCallback;
import com.one.blocks.security.authz.AuthorizeService;
import com.one.blocks.security.util.SubjectHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author linfuxin Created on 2022-02-14 14:20:52
 */
@Component
public class AuthorizeServiceImpl implements AuthorizeService, AccessCallback {

    @Autowired
    private SysMenuManager sysMenuManager;

    @Autowired
    private SysRoleManager sysRoleManager;

    @Override
    public boolean checkPermission(String permission) {
        Integer userId = SubjectHelper.getSubjectId();

        SysRole sysRole = sysRoleManager.getByUserId(userId);
        if (sysRole == null) {
            return false;
        }

        SubjectRoleHelper.setSysRole(sysRole);

        // 平台管理员角色直接通过校验
        if (RoleTypeEnum.PLATFORM_ADMIN.match(sysRole.getType())) {
            return true;
        }

        // 其余角色查询权限进行校验
        Set<String> permissionList = sysMenuManager.listPermission(sysRole);
        return CollectionUtils.isNotEmpty(permissionList) && permissionList.contains(permission);
    }

    @Override
    public void accessCompleted() {
        SubjectRoleHelper.clear();
    }
}
